package com.project.nemesis;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SaveFile extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		try {		
			
			String plist = req.getParameter("plist");
			String fileName = req.getParameter("fileName");
			
			
			BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
			Iterator<BlobInfo> iterator = null;
			BlobInfo info = null;
			iterator = new BlobInfoFactory().queryBlobInfos();
	  	
			while(iterator.hasNext()){
		      	info = iterator.next(); 
		      	if(fileName.toString().equals(info.getFilename().toString())){
		      		blobstoreService.delete(info.getBlobKey());	
		      		break;
		      	}   
	      	
			}    
	        
	        byte[] inFile = plist.getBytes();
	        	

			  // Get a file service
			  FileService fileService = FileServiceFactory.getFileService();

			  // Create a new Blob file with mime-type "text/plain"
			  AppEngineFile file = fileService.createNewBlobFile("text/plain", fileName);

			  // Open a channel to write to it
			  boolean lock = true;						  
			  FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);

			  writeChannel.write(ByteBuffer.wrap(inFile));
			  writeChannel.closeFinally();
			  
	        
		} catch (Exception ex) {
			
			throw new ServletException(ex);
		}
	}
}